package com.androiddelphi;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public  class RegistrarAPP extends Activity implements OnClickListener {

	Button btnConfirma;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_registrar_app);
		btnConfirma= (Button) findViewById(R.id.btnConfirmaRegistroAPP);
		btnConfirma.setOnClickListener(this);	

	}
	
	@Override
	public void onClick(View v) {
		
		new Thread(){
			public void run(){
				EditText edtNome = (EditText)findViewById(R.id.edtNomeRegistroAPP);
				EditText edtEmail = (EditText)findViewById(R.id.edtEmailRegistroAPP);
				EditText edtTelefone = (EditText)findViewById(R.id.edtTelefoneRegistroAPP);
				
				postHttp(edtNome.toString(), edtEmail.toString(), edtTelefone.toString());
			}
		}.start();
		
		
	}
	
	public void postHttp(String nome, String email, String telefone){
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://localhost:8080/AndroidDelphiWeb");
		
		try{
			ArrayList<NameValuePair> valores = new ArrayList<NameValuePair>();
			valores.add(new BasicNameValuePair("nome", nome));
			valores.add(new BasicNameValuePair("email", email));
			valores.add(new BasicNameValuePair("telefone", telefone));
			
			httpPost.setEntity(new UrlEncodedFormEntity(valores));
			final HttpResponse resposta = httpClient.execute(httpPost);
			
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					try {
						Toast.makeText(getBaseContext(), EntityUtils.toString(resposta.getEntity()), Toast.LENGTH_SHORT).show();
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
				}
			});
			
		}catch(ClientProtocolException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
}
